const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const proxy = require('http-proxy-middleware')
const session = require('express-session')
const connectRedis = require('connect-redis')
const routes = require('./router')

const autoJumpToCity = require('./middleware/autoJumpToCity')
// const ipBlock = require('./middleware/ipBlock')
const sendErr = require('./middleware/sendErr')

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
const { proxy: target, redis: redisConfig } = require('./config.js')

const app = express()
const RedisStore = connectRedis(session)

// 测试
app.get('/w.html', (req, res) => {
  res.send('hello word')
})

// 制定ip访问
// app.use(ipBlock)

// 打印访问IP
// app.use((req, res, next) => {
//   const currentIp = (
//     req.headers['x-forwarded-for'] ||
//     req.connection.remoteAddress ||
//     req.socket.remoteAddress ||
//     req.connection.socket.remoteAddress
//   ).split(',')[0]
//   console.log(currentIp)
//   next()
// })

// session
app.use(
  session({
    store: new RedisStore(redisConfig),
    secret: 'feast_website',
    cookie: {
      maxAge: 86400000 * 3
    },
    saveUninitialized: false,
    resave: false
  })
)

// 自定义路由
app.use('/api', routes)

// 请求代理
if (config.dev) {
  app.use(
    '/api/*',
    proxy({
      target,
      changeOrigin: true
      // pathRewrite: {
      //   '^/web/api': '/api' // rewrite path
      // }
    })
  )
}

// 跳转城市
app.use(autoJumpToCity)

async function start() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  const { host, port } = nuxt.options.server

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  // Give nuxt middleware to express
  app.use(nuxt.render)

  // 错误报告
  app.use((err, req, res, next) => {
    if (err) {
      res.status(500)
      // req.originalUrl
      const { originalUrl } = req

      const text = `
        > 地址：${originalUrl}
        > 人人宴node${originalUrl}错误：${err.message || '发生错误'}`
      sendErr('人人宴官网错误', text)
    }
    next()
  })

  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}
start()
